<template>
  <div class="login-container">
    <div>
      <h3 class="title">
        <!-- <select class="form-control companyList"  v-model="pvdNo" >
                      <template v-for="(x,index) in companys">
                          <option :value="x.ORGID"
                              v-text="x.ORGNAME" v-if="index == 0 " selected
                          >
                          </option>
                          <option :value="x.ORGID"
                              v-text="x.ORGNAME" v-else
                          ></option>
                      </template>
                  </select> -->
        <span v-text="loginID"></span>
      </h3>
      <h3 class="orgTitle">
        <span v-text="orgName"></span>
      </h3>
    </div>
    <el-form class="card-box login-form" autoComplete="on" :model="loginForm" :rules="loginRules" ref="loginForm" label-position="left">
      <el-tabs type="border-card">
          <el-tab-pane label="账号登录" >
              <el-form-item prop="username" v-if="this.companys.length > 1" style="margin-bottom:22px;">
                  <span class="svg-container svg-container_login">
                    <icon-svg icon-class="yonghuming" />
                  </span>
                  <el-select v-model="pvdNo" filterable autoComplete="on" @change="mechanismchange" style="width:85%">
                    <el-option v-for="item in companys" :key="item.ORGID" :label="item.ORGNAME" :value="item.ORGID">
                    </el-option>
                  </el-select>
              </el-form-item>

              <el-form-item prop="username" style="margin-bottom:22px;">
                  <span class="svg-container svg-container_login">
                    <icon-svg icon-class="yonghuming" />
                  </span>
                  <el-input name="username" type="text" v-model="loginForm.username" autoComplete="on" placeholder="请输入正确的用户名" />
              </el-form-item>

              <el-form-item prop="password"  style="margin-bottom:22px;">
                  <span class="svg-container">
                    <icon-svg icon-class="mima" />
                  </span>
                  <el-input name="password" :type="pwdType" @keyup.enter.native="handleLogin" v-model="loginForm.password" autoComplete="on"
                    placeholder="请输入密码" />
                  <span class='show-pwd' @click='showPwd'><icon-svg icon-class="yanjing" /></span>
              </el-form-item>

              <div class="codeBox" v-show="showDialog">
                  <input type="text" placeholder="请输入验证码"  style="border: 1px solid #dcdcdc; border-radius: 4px; width: 70%; margin-right: 10px;" @blur="checkLpicma" v-model="codeValue">
                  <input type="button" id="code" @click="createCode"  class="verification1" v-model="checkCode"/> <br>
                  <p v-show="codeTip" style="color: red; font-size: 12px; padding: 10px; " >验证码错误，请重新填写哦</p>
              </div>
          </el-tab-pane>
        
      </el-tabs>

      <el-button type="primary" style="width:100%;margin-bottom:30px; margin-top: 20px" :loading="$store.state.isloading" @click.native.prevent="handleLogin">登录</el-button>
         <p style="color: #fff; text-align: center; font-size: 13px;"> © 杭州安创科技有限公司</p>
      </el-form>
  </div>
</template>

<script>
// import { isvalidUsername } from '@/utils/validate'
import { mapGetters } from "vuex";
import loginSafe from "@/assets/login/safe.jpeg";
import apiBase from "@/api/apiBase.js";
import encoding from "text-encoding";
export default {
  name: "login",
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value == null) {
        callback(new Error("请输入正确的用户名"));
      } else {
        callback();
      }
    };

    const validatePassword = (rule, value, callback) => {
      if (value.length < 0) {
        callback(new Error("密码不能小于6位"));
      } else {
        callback();
      }
    };

    return {
      code: null,
      loginSafe,
      loginForm: {
        username: null,
        password: null,
        mechanismid: null,//机构号
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername }
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword }
        ]
      },
      pwdType: "password",
      loading: false,
      showDialog: false,
      companys: [],
      pvdNo: null,
      timeout: null,
      orgName: null,
      loginID: null,
      orgID: null,
      codeErro: 0,
      codeValue: "",
      checkCode: "",
      codeTip: false,
      systemnameValue: false,
    };
  },
  methods: {
    showPwd() {
      if (this.pwdType === "password") {
        this.pwdType = "";
      } else {
        this.pwdType = "password";
      }
    },

    handleLogin(e) {
      //登录
      e.preventDefault();
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.$store.state.isloading = true;
          var data = {
            USRORGID: this.pvdNo,
            USRLOGINNAME: this.loginForm.username,
            USRPASSWD: this.loginForm.password
          };

          apiBase.DoService(
            data,
            apiBase.getApiAdress().Login.Login,
            res => {
              this.$store.state.isInitPassWord =
                res.data.content.isInitPassWord;
              var isInitPassWordCode = this.$store.state.isInitPassWord;
              this.$store.state.sessionkey = res.data.content.SessionKey;
              this.$store.state.orginCode = res.data.content.OrganNumber;
              var sessionke = this.$store.state.sessionkey;
              // 在有多个机构的情况下，在登录的时候把orgname存在缓存中
              if(this.companys && this.companys.length > 1){
                this.companys.forEach(item => {
                  if(item.ORGID === res.data.content.OrgId){
                    localStorage.setItem("orgname", item.ORGNAME);
                  }
                });
              }
              this.$store.state.userAuthorization = localStorage.setItem(
                "Authorization",
                sessionke
              );
              var userName = localStorage.setItem(
                "name",
                this.loginForm.username
              );
              var pvdNo = localStorage.setItem(
                "pvdid",
                this.pvdNo
              );
              localStorage.setItem(
                "username",
                res.data.content.UserName
              );
              var orginCode = localStorage.setItem(
                "orginCode",
                res.data.content.OrganNumber
              );
              this.$store.state.loginPassword = this.loginForm.password;
              // var password = localStorage.setItem(
              //   "password",
              //   this.loginForm.password
              // );

              var isInitPassWord = localStorage.setItem(
                "isInitPassWord",
                isInitPassWordCode
              );
              sessionStorage.setItem("loginForm", this.$route.path);

              if (this.showDialog == true) {
                if (this.codeValue.toUpperCase() == this.checkCode) {
                  clearTimeout(this.timeout);
                  this.timeout = setTimeout(() => {
                    this.$store.state.isloading = false;

                    if (this.$store.state.isInitPassWord == true) {
                      this.$router.push({ path: "/dashboard" });
                    } else {
                      this.$router.push({ path: "/dashboard" });
                      window.location.reload();
                    }
                  }, 2000 * Math.random());
                } else {
                  this.$store.state.isloading = false;
                  this.$message.error("请填写正确的验证码");
                  //alert( '验证码错误')
                }
              } else if (this.showDialog == false) {
                clearTimeout(this.timeout);
                this.timeout = setTimeout(() => {
                  this.$store.state.isloading = false;
                  //this.$router.push({ path: "/dashboard" });
                  if (this.$store.state.isInitPassWord == true) {
                    this.$router.push({ path: "/dashboard" });
                  } else {
                    this.$router.push({ path: "/dashboard" });
                    window.location.reload();
                  }
                }, 2000 * Math.random());
              } else {
                console.log(res.data.msg);
              }
            },
            res => {
              this.$message.error("登录用户不存在或登录信息出错");
              // alert(res.data.msg);
              this.$store.state.isloading = false;
              this.codeErro++;

              if (this.codeErro === 3) {
                this.codeErro = 0;
                this.showDialog = true;
                this.loginForm.password = "";
              }
            }
          );
        }
      });
    },

    // 图片验证码
    createCode() {
      var code = "";
      var codeLength = 4; //验证码的长度
      var random = new Array(
        0,
        1,
        2,
        3,
        4,
        5,
        6,
        7,
        8,
        9,
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H",
        "I",
        "J",
        "K",
        "L",
        "M",
        "N",
        "O",
        "P",
        "Q",
        "R",
        "S",
        "T",
        "U",
        "V",
        "W",
        "X",
        "Y",
        "Z"
      ); //随机数
      for (var i = 0; i < codeLength; i++) {
        //循环操作
        var index = Math.floor(Math.random() * 36); //取得随机数的索引（0~35）
        code += random[index];
      }
      this.checkCode = code;
    },
    checkLpicma() {
      this.codeValue.toUpperCase(); //取得输入的验证码并转化为大写
      if (this.codeValue.toUpperCase() == this.checkCode) {
        this.codeTip = false;
      } else {
        this.codeTip = true;
        this.loginForm.password = "";
      }
    },
    

    getCompany() {
      //获取所有机构
      this.orgName = null;
      var data = {};
      apiBase.DoService(data, apiBase.getApiAdress().Login.QueryOrgan, res => {
        this.companys = res.data.content;
        if(this.companys && this.companys.length > 1){
          if(localStorage.getItem("pvdid") == null){
            this.pvdNo = this.companys[0].ORGID;
          }else{
            this.pvdNo = localStorage.getItem("pvdid");
          };
          this.mechanismchange(this.pvdNo);
        }else{
          this.pvdNo = this.companys[0].ORGID;
          this.orgName = this.companys[0].ORGNAME;
          localStorage.setItem("orgname", this.orgName);
        }
      });
    },
    //机构号发生改变触发的事件
    mechanismchange(val){
      this.companys.forEach(item => {
        if(item.ORGID === val){
          this.orgName = item.ORGNAME;
        }
      });
      
    },

    getSystemname() {
      var data = {};
      // this.loginID = "浙江省殡葬综合管理平台";
      // this.loginID = "义乌市逝者部门联办平台";
      this.loginID = null;
      document.title = this.loginID;
      localStorage.setItem("sysname", this.loginID);
      apiBase.DoService(
        data,
        apiBase.getApiAdress().Login.GetSystemname,
        res => {
          this.loginID = res.data.content.systemname;
          document.title = this.loginID;
          localStorage.setItem("sysname", this.loginID);
        }
      );
    },

    getTest() {
      var data = {};
      apiBase.DoService(data, apiBase.getApiAdress().Login.QueryOrgan, res => {
        console.log(res.data.code);
      });
    }
  },
  mounted() {
    // window.location.reload()
    this.createCode();
    this.loginForm.username = localStorage.getItem("name");
  },
  created() {
    this.getCompany();
    this.getSystemname();
    // window.location.reload()
  },
  computed: {
    ...mapGetters(["sessionkey"])
  }
};
</script>

<style rel="stylesheet/scss" scoped lang="scss">
@import "src/styles/mixin.scss";
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;
#code {
  font-family: Arial, 宋体;
  font-style: italic;
  color: green;
  border: 0;
  padding: 2px 3px;
  letter-spacing: 3px;
  font-weight: bolder;
  background: #e5e5e5;
  border-radius: 4px;
}

select::-ms-expand {
  //ie下啦箭头隐藏
  display: none;
}
.el-tabs__nav-scroll {
  .el-tabs__nav {
    width: 100%;
    .el-tabs__item {
      width: 51%;
    }
  }
}
.companyList {
  width: auto;
  display: inline-block;
  outline: medium none;
  border: none;
  -webkit-appearance: none;
  -moz-appearance: none;
  // appearance: none;
  text-align: center;
  background-color: transparent;
  height: auto;
  padding: 6px 0px;
  font-size: 26px;
  line-height: normal;
  color: white;
  text-align-last: right;
}
.codeBox {
  padding-bottom: 10px;
  span.codeImg {
    display: inline-block;
    border: 1px solid #dcdcdc;
    width: 40%;
    padding: 12px;
    border-radius: 4px;
    background: #d4d1d1;
    text-align: center;
    cursor: pointer;
    margin-left: 20px;
  }
}

.login-container {
  box-sizing: border-box;
  @include relative;
  height: 100vh;
  background-color: $bg;
  background-image: url("loginBg.jpg");
  background-position: center;
  background-size: cover;
  input:-webkit-autofill {
    // -webkit-box-shadow: 0 0 0px 1000px #293444 inset !important;
    -webkit-text-fill-color: #fff !important;
  }
  input {
    background: transparent;
    border: 0px;
    -webkit-appearance: none;
    border-radius: 0px;
    padding: 12px 5px 12px 15px;
    // color: $light_gray;
    height: 47px;
  }
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;
  }
  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;
  }
  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
    &_login {
      font-size: 20px;
    }
  }
  .title {
    font-size: 40px;
    font-weight: 400;
    color: $light_gray;
    margin: 0px auto 20px auto;
    padding-top: 80px;
    text-align: center;
    font-weight: bold;
  }
  .orgTitle {
    font-size: 30px;
    color: $light_gray;
    margin: 0px auto;
    text-align: center;
    font-weight: bold;
  }
  .login-form {
    position: absolute;
    left: 0;
    right: 0;
    width: 400px;
    padding: 35px 35px 15px 35px;
    margin: 20px auto;
  }
  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
  }
  .thirdparty-button {
    position: absolute;
    right: 35px;
    bottom: 28px;
  }
}
</style>
